import { reactive, ref, computed } from 'vue'
import storage from "./storage";
import apiUser from "@/api/user";

const useStore = (() => {
  const state = reactive({
    token: "",
    user: {
      storeName: "",
      userType: -1, // 用户类型 [32：普通客户, 33：会员]
      bookEnabled: 0, // 门店是否开启了预订（只有门店开启了预订功能，才显示预订按钮）
      storeMemberEnabled: 0, // 门店是否开启了会员功能（只有门店开启了会员，并且当前用户是会员才能使用会员钱包余额支付）
    },
    qr: {}, // { tableId, storeId, deviceId }
    orderType: null, // 点餐类型 [11：堂食, 31：预订]
    payMethod: 11, // 付款方式 [1：商家扫付款码, 2：用户扫码支付, 11：微信小程序]
    walletAmount: 0, // 用户钱包余额
    menuList: ref([]),
    expectAt: "",
  });

  const getters = {
    isLogin: computed(() => { return state.token !== ""; }),
    isOrderType: computed(() => { return state.orderType !== null; }),
    isBook: computed(() => { return state.user.bookEnabled === 1; }),
    isMember: computed(() => { return state.user.userType === 33; }),
    isStoreMember: computed(() => { return state.user.storeMemberEnabled === 1; })
  };

  const actions = {
    initData() { },
    saveToken(v) {
      state.token = v;
    },
    saveQrInfo(v) {
      state.qr = {};
      for (let n in v) {
        state.qr[n] = v[n];
      }
    },
    updateWalletAmount() {
      return new Promise(async (success, error) => {
        try {
          let data = await apiUser.getWalletAmount();
          state.walletAmount = data.walletAmount;
          success();
        } catch (err) {
          error(err);
        }
      });
    },
    loginOut() {
      state.token = "";
      state.qr = {};
      state.orderType = null;
      state.walletAmount = 0;
    },
    login(json) {
      return new Promise(async (success, error) => {
        uni.login({
          provider: "weixin",
          success: async (res) => {
            if (res.code) {
              try {
                let data = await apiUser.login(Object.assign({ jsCode: res.code }, json));
                state.token = data.accessToken;
                state.user.storeName = data.storeName;
                state.user.userType = data.userType;
                state.user.bookEnabled = data.bookEnabled;
                state.user.storeMemberEnabled = data.storeMemberEnabled;
                state.menuList = [];
                success();
              } catch (err) {
                error(err);
              }
            } else {
              error("code不存在");
            }
          },
          fail(err) {
            error(err);
          }
        });

      });
    }
  };
  return { state, ...getters, ...actions };
})();

export default useStore;
